package com.muy.redis.utils;

import com.intellij.credentialStore.CredentialAttributes;
import com.intellij.credentialStore.CredentialAttributesKt;
import com.intellij.credentialStore.Credentials;
import com.intellij.ide.passwordSafe.PasswordSafe;
import org.apache.commons.lang.StringUtils;

/**
 * @Author jiyanghuang
 * @Date 2023/9/28 22:54
 */
public class PasswordUtils {

    public static CredentialAttributes createCredentialAttributes(String connectionId) {
        return new CredentialAttributes(
                CredentialAttributesKt.generateServiceName("MrRedisTool", connectionId)
        );
    }

    /**
     * 获取密码
     *
     * @return 密码, 如果是 "" 则返回 null
     */
    public static String retrievePassword(String connectionId) {
        CredentialAttributes credentialAttributes = createCredentialAttributes(connectionId);
        String password = PasswordSafe.getInstance().getPassword(credentialAttributes);
        return StringUtils.isEmpty(password) ? null : password;
    }

    /**
     * 保存密码, 如果 password 是 null 或者 "", 则表示移除 password
     */
    public static void savePassword(String connectionId, String password) {
        CredentialAttributes credentialAttributes = createCredentialAttributes(connectionId);
        Credentials credentials = null;
        if (StringUtils.isNotEmpty(password)) {
            credentials = new Credentials(connectionId, password);
        }
        PasswordSafe.getInstance().set(credentialAttributes, credentials);
    }
}
